package cz.muni.fi.pa165.soap.client.editPannel;


import cz.muni.fi.pa165.soap.AdminRole;
import cz.muni.fi.pa165.soap.EmployeeDTO;
import cz.muni.fi.pa165.soap.func.Funcs;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.ResourceBundle;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;

/**
 *
 * @author shifty
 */
public class EditEmployee extends JPanel {
   
    private ResourceBundle rb;
    private EmployeeDTO employee;
    
    public EditEmployee(ResourceBundle rb, EmployeeDTO emp) {
        this.rb=rb;
        this.employee=emp;
        init();
    }
    
    private void init() {
        setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
        setToolTipText(rb.getString("main.employee")+" - "+( (employee!=null)?employee.getName():rb.getString("form.new") ));
        
        nameLabel = new JLabel(rb.getString("table.name"));
        birthDateLabel = new JLabel(rb.getString("table.birthDate"));
        saveButton = new JButton(rb.getString("form.save"));
        birthDayLabel  = new JLabel(rb.getString("table.day"));
        birthMonthLabel= new JLabel(rb.getString("table.month"));
        birthYearLabel = new JLabel(rb.getString("table.year"));
        roleLabel = new JLabel(rb.getString("table.role"));
        passwordLabel = new JLabel(rb.getString("table.password"));
        
        Box name = Box.createHorizontalBox();
        name.add(nameLabel);
        name.add(nameField);
        Funcs.setFixedSize(nameLabel, defaultSize);
        Funcs.setFixedSize(nameField, defaultSize);
        Box birthDate = Box.createHorizontalBox();
        birthDate.add(birthDateLabel);
        Funcs.setFixedSize(birthDateLabel, defaultSize);
        Dimension dim = new Dimension(50, 20);
        Box birth = Box.createHorizontalBox();
        birth.add(birthDayLabel);
        birth.add(dayField);
        birth.add(birthMonthLabel);
        birth.add(monthField);
        birth.add(birthYearLabel);
        birth.add(yearField);
        Funcs.setFixedSize(birthDayLabel, dim);
        Funcs.setFixedSize(dayField, dim);
        Funcs.setFixedSize(birthMonthLabel, dim);
        Funcs.setFixedSize(monthField, dim);
        Funcs.setFixedSize(birthYearLabel, dim);
        Funcs.setFixedSize(yearField, dim);
        Box password = Box.createHorizontalBox();
        password.add(passwordLabel);
        password.add(passwordField);
        
        Box role = Box.createHorizontalBox();
        role.add(roleLabel);
        String[] rolesTypes = { rb.getString("MANAGER"), rb.getString("DELIVERY_BOY") };
    
        roleBox = new JComboBox(rolesTypes);

        role.add(roleBox);
        
        
        Box save = Box.createHorizontalBox();
        save.add(saveButton);
        saveButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    EmployeeDTO emp = getValues();
                    onSave.setObject(emp);
                    onSave.execute();
                } catch(DatatypeConfigurationException | IllegalArgumentException dce) {
                    JOptionPane.showMessageDialog((JButton)e.getSource(),
                        rb.getString("form.error.parse.info"),
                        rb.getString("form.error.parse"),
                        JOptionPane.WARNING_MESSAGE);
                } catch(IllegalStateException ise) {
                    JOptionPane.showMessageDialog((JButton)e.getSource(),
                        rb.getString(ise.getMessage()),
                        rb.getString("form.warning"),
                        JOptionPane.WARNING_MESSAGE);
                }  
            }
        });
        add(name);
        add(birthDate);
        add(birth);
        add(password);
        add(role);
        add(save);
        add(Box.createVerticalGlue());
        
        setValues();
    }
    
    private void setValues(){
        if(employee == null) {
            return;
        }
        nameField.setText(employee.getName());
        XMLGregorianCalendar cal = employee.getBirthDate();
        dayField.setText(cal.getDay()+"");
        monthField.setText(cal.getMonth()+"");
        yearField.setText(cal.getYear()+"");
        passwordField.setText(employee.getPassword());
        if(employee.getRole().equals(AdminRole.MANAGER)) {
            roleBox.setSelectedIndex(0);
        } else {
            roleBox.setSelectedIndex(1);
        }
    }
    
    private EmployeeDTO getValues() throws DatatypeConfigurationException {
        String name = nameField.getText();
        String pass = passwordField.getText();
        int day = Integer.parseInt(dayField.getText());
        int month = Integer.parseInt(monthField.getText());
        int year = Integer.parseInt(yearField.getText());
        
        if(name.isEmpty() || pass.isEmpty()) {
            throw new IllegalStateException("form.warning.input.empty");
        }

        GregorianCalendar c = new GregorianCalendar();
        c.set(Calendar.YEAR,year);
        c.set(Calendar.MONTH, month-1);
        if(c.get(Calendar.YEAR) != year) {
            throw new IllegalStateException("form.error.parse.month");
        }
        c.set(Calendar.DATE,day);
        if(c.get(Calendar.YEAR) != year || c.get(Calendar.MONTH) != month-1) {
            throw new IllegalStateException("form.error.parse.day");
        }
        GregorianCalendar c2 = (GregorianCalendar) c.clone();
        Calendar c3 = Calendar.getInstance();
        c3.add(Calendar.YEAR, -15);
        if(c.getTime().after(c3.getTime())) {
            throw new IllegalStateException("form.error.parse.young");
        }
        c3.add(Calendar.YEAR, -84);
        if(c.getTime().before(c3.getTime())) {
            throw new IllegalStateException("form.error.parse.old");
        }
        EmployeeDTO emp = new EmployeeDTO();
        if(employee != null) {
            emp.setId(employee.getId());
        }
        emp.setName(name);
        emp.setPassword(pass);
        emp.setBirthDate(DatatypeFactory.newInstance().newXMLGregorianCalendar(c));
        if(roleBox.getSelectedIndex()==0) {
            emp.setRole(AdminRole.MANAGER);
        } else {
            emp.setRole(AdminRole.DELIVERY_BOY);
        }
        return emp;
    }
    
    private Calendar cal = Calendar.getInstance();
    
    private Dimension defaultSize = new Dimension(150, 20);
    
    private JTextField nameField = new JTextField();
    private JTextField dayField = new JTextField();
    private JTextField monthField = new JTextField();
    private JTextField yearField = new JTextField();
    private JTextField passwordField = new JTextField();
    
    private JComboBox roleBox;
    
    private JLabel nameLabel;
    private JLabel birthDateLabel;
    private JLabel birthDayLabel;
    private JLabel birthMonthLabel;
    private JLabel birthYearLabel;
    private JLabel roleLabel;
    private JLabel passwordLabel;
    private JButton saveButton;
    
    private OnSave<EmployeeDTO> onSave;
    
    public void onSave(OnSave<EmployeeDTO> al) {
        onSave = al;
    }
}
